<template>
  <form action="/">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入标签进行搜索"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>

  <van-divider content-position="left">已选标签</van-divider>
  <div v-if="activeIds.length === 0" >请选择标签</div>
  <van-row gutter="20">
    <van-col v-for="tag in activeIds">
      <van-tag :show="show" closeable size="medium" type="primary" @close="close(tag)">
        {{ tag }}
      </van-tag>
    </van-col>
  </van-row>

  <van-divider content-position="left">选择标签</van-divider>

  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />

  <div style="padding: 18px">
    <van-button block plain type="primary" @click="doSearch">搜索</van-button>
  </div>

</template>

<script setup lang="ts">
import { ref } from 'vue';
import {useRouter} from "vue-router";

const router = useRouter();

const searchText = ref('');
const show = ref(true);

// 已选中的标签
const activeIds = ref([]);
const activeIndex = ref(0);

// 标签列表
const originTagList = ref([
  {
    text: '性别',
    children: [
      { text: '男', id: '男' },
      { text: '女', id: '女' },
    ],
  },
  {
    text: '年级',
    children: [
      { text: '大一', id: '大一' },
      { text: '大二', id: '大二' },
      { text: '大三', id: '大三' },
      { text: '大四', id: '大四' },
    ],
  },
  {
    text: '语言',
    children: [
      { text: 'Java', id: 'Java' },
      { text: 'JavaScript', id: 'JavaScript' },
      { text: 'TypeScript', id: 'TypeScript' },
      { text: 'Python', id: 'Python' },
      { text: 'PHP', id: 'PHP' },
      { text: 'C++', id: 'C++' },
      { text: 'C#', id: 'C#' },
    ]
  }
]);

let tagList = ref(JSON.parse(JSON.stringify(originTagList.value)));

const onSearch = () => {
  tagList.value = originTagList.value.map(parentTag => {
    // 创建新的父标签对象避免污染原始数据
    return {
      ...parentTag,
      children: parentTag.children.filter(childTag =>
        // 改为包含 id 的搜索（更符合标签搜索逻辑）
        childTag.text.includes(searchText.value) ||
        childTag.id.includes(searchText.value)
      )
    };
  // 添加这行过滤空分类
  }).filter(parentTag => parentTag.children.length > 0);
};
const onCancel = () => {
  searchText.value = '';
  tagList.value = JSON.parse(JSON.stringify(originTagList.value));
};

//删除标签
const close = (tag:number) => {
  activeIds.value = activeIds.value.filter(item => {
    return item !== tag;
  })
};

/**
 * 跳转到搜索结果页面
 */
const doSearch = () => {
  router.push({
    path: '/user/list',
    query: {
      tags: activeIds.value,
    }
  })
}

</script>

<style scoped>

</style>